<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Core\JWT;
use App\Models\User;

class AuthController
{
    public function login(): void
    {
        $data = Request::validate([
            'username' => 'required',
            'password' => 'required|min:6'
        ]);
        
        $user = User::findByUsername($data['username']);
        
        if (!$user || !User::verifyPassword($data['password'], $user['password'])) {
            Response::error('用户名或密码错误', 401);
        }
        
        // 获取用户权限
        $permissions = User::getUserPermissions($user['id']);
        
        // 生成JWT令牌
        $token = JWT::encode([
            'user_id' => $user['id'],
            'username' => $user['username'],
            'role' => $user['role']
        ]);
        
        // 移除敏感信息
        unset($user['password']);
        $user['permissions'] = $permissions;
        
        Response::success([
            'token' => $token,
            'user' => $user
        ], '登录成功');
    }

    public function logout(): void
    {
        Response::success(null, '登出成功');
    }

    public function current(): void
    {
        $currentUser = $GLOBALS['current_user'] ?? null;
        
        if (!$currentUser) {
            Response::error('未登录', 401);
        }
        
        // 获取用户权限
        $permissions = User::getUserPermissions($currentUser['id']);
        
        unset($currentUser['password']);
        $currentUser['permissions'] = $permissions;
        
        Response::success($currentUser);
    }
}

